package http

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
)

var Key = "6F361CB8C6E0B33C89CAE59A1D3F944A"
var domain = "http://118.26.0.81:10029/api/"

const HttpProxyUrl = "http://127.0.0.1:8888"

// QueryParams 定义传参
var QueryParams map[string]string

type Authentication struct {
	Num      string `json:"mun"`
	Password string `json:"password"`
	Time     string `json:"time"`
}

// Param 定义请求参数结构体
type Param struct {
	PageNo       int `form:"pageNo" json:"pageNo" binding:"required"`
	PageSize     int `form:"pageSize" json:"pageSize" binding:"required"`
	AssignType   int `form:"assignType" json:"assignType"`
	HuifangState int `form:"huifangState" json:"huifangState" binding:"required"`
}

func main() {
	//设置路由
	router := gin.Default()
	router.POST("list", func(c *gin.Context) {
		//var param Param
		//if err := c.ShouldBind(&param); err == nil {
		//	lists := sendApi(param)
		//	c.JSON(http.StatusOK, gin.H{
		//		"code": 200,
		//		"data": string(lists),
		//	})
		//} else {
		//	log.Fatalln(err)
		//}
		QueryParams = make(map[string]string)
		QueryParams["pageSize"] = c.PostForm("pageSize")
		QueryParams["pageNo"] = c.PostForm("pageNo")
		QueryParams["huifangState"] = c.PostForm("huifangState")
		QueryParams["assignType"] = c.DefaultPostForm("assignType", "0")
		lists := sendApi(mapToQuery(QueryParams))
		ret := string(lists)
		c.String(200, ret)
	})
	router.Run(":8088")
}

//将map的键值对转化为abc=123&cse=345
func mapToQuery(params map[string]string) (paramStr string) {
	slice := make([]string, len(params))
	for k, v := range params {
		slice = append(slice, fmt.Sprintf("%s=%s", k, v))
	}
	paramStr = strings.Join(slice, "&")
	return
}

//此方法请求接口用
func sendApi(param string) []byte {
	fmt.Printf("para=>%+v\n", param)
	ProxyURL, _ := url.Parse(HttpProxyUrl)
	client := &http.Client{
		//设置代理
		Transport: &http.Transport{
			Proxy: http.ProxyURL(ProxyURL),
		},
	}
	//发送请求
	req, _ := http.NewRequest("POST", domain+"queryAllHandleList", strings.NewReader(param))
	//获取请求头
	auth := genAuth()
	//设置请求头信息
	req.Header.Add("authentication", auth)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	return body
}

func genAuth() string {
	var auth Authentication
	auth.Num = genRandom()
	auth.Time = strconv.FormatInt(time.Now().Unix(), 10)
	auth.Password = genPassword(auth)
	//结构体转化为字符串
	data, err := json.Marshal(auth)
	if err != nil {
		//处理错误信息
		log.Fatalln(err)
	}
	return string(data)
}

//生成随机字符串
func genRandom() (str string) {
	//设置随机因子
	rand.Seed(time.Now().Unix())
	return strconv.Itoa(100000 + rand.Intn(1099999-100000))
}

//生成password
func genPassword(auth Authentication) (pass string) {
	//拼接签名字符串 key+time+mun
	pass = fmt.Sprintf("%s%s%s", Key, auth.Time, auth.Num)
	//转切片
	sl := strings.Split(pass, "")
	//对字符串进行升序排序
	sort.Strings(sl)
	//进行md5
	str1 := strings.Join(sl, "")
	result := md5.Sum([]byte(str1))

	pass = fmt.Sprintf("%x", result)
	//转大写
	pass = strings.ToUpper(pass)
	return
}
